package com.example.easycharge.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.easycharge.entity.Customer;
import com.example.easycharge.error.AttributeNotFoundError;
import com.example.easycharge.error.UserNotFoundError;
import com.example.easycharge.error.VehicleNotWorkError;
import com.example.easycharge.entity.Bill;
import com.example.easycharge.repository.BillRepository;
import com.example.easycharge.repository.CustomerRepository;
import com.example.easycharge.repository.VehicleRepository;
import com.example.easycharge.service.BillService;
import com.example.easycharge.service.ChargeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Tag(name = "用户接口组")
@RestController
@RequestMapping("user")
public class CustomerController {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private ChargeService chargeService;
    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    private BillService billService;

    @Operation(description = "查询用户的信息，是一个管理员接口")
    @GetMapping("admin/{userId}")
    public Customer getCustomerById(@PathVariable("userId") long userId) throws UserNotFoundError {
        if (customerRepository.countCustomerByUserId(userId) == 0) {
            throw new UserNotFoundError();
        } else {
            Customer user = customerRepository.findCustomerByUserId(userId);
            user.setUserPassword("*");
            return user;
        }
    }

    @Operation(description = "查询当前用户申请充电的车辆的信息（预计等待时间、电量百分比等）")
    @GetMapping("/totalVehicle")
    public List<JSONObject> getAllVehicleInfo(HttpServletRequest httpServletRequest) throws VehicleNotWorkError {
        long customerId = (long) httpServletRequest.getAttribute("customerId");
        List<JSONObject> resultList = chargeService.getAllVehicleInfo(customerId);
        if (resultList == null || resultList.size() == 0) {
            throw new VehicleNotWorkError();
        }
        return resultList;
    }

    @Operation(description = "查询某个待充电/已充电车辆的信息")
    @GetMapping("/vehicle/{vehicleId}")
    public JSONObject getSigVehicleInfo(@PathVariable("vehicleId") long vehicleId) throws VehicleNotWorkError {
        JSONObject resultRequest = chargeService.getSigVehicleInfo(vehicleId);
        if (resultRequest == null) {
            throw new VehicleNotWorkError();
        }
        return resultRequest;
    }

    @Operation(description = "修改用户信息的接口，可以改动的值有【userPassword、userNickName、userPhone、autoSelect、autoFix】，试图更改无法改动的或者不存在的数据将会返回错误码")
    @PutMapping("/setting/{changeItem}/{newValue}")
    public JSONObject updateUserDetail(HttpServletRequest httpServletRequest,
                                       @PathVariable("changeItem") String changeItem,
                                       @PathVariable("newValue") String newValue) throws AttributeNotFoundError, UserNotFoundError {
        long userId = (long) httpServletRequest.getAttribute("customerId");
        Customer user = customerRepository.findCustomerByUserId(userId);
        int customerExist = customerRepository.countCustomerByUserId(userId);
        if (customerExist == 0) {
            throw new UserNotFoundError();
        }
        String oldValue;
        switch (changeItem) {
            case "userPassword":
                oldValue = user.getUserPassword();
                user.setUserPassword(encoder.encode(newValue));
                break;
            case "userNickName":
                oldValue = user.getUserNickName();
                user.setUserNickName(newValue);
                break;
            case "userPhone":
                oldValue = user.getUserPhone();
                user.setUserPhone(newValue);
                break;
            case "autoSelect":
                oldValue = user.isAutoSelect() + "";
                user.setAutoSelect(Boolean.parseBoolean(newValue));
                break;
            case "autoFix":
                oldValue = user.isAutoFix() + "";
                user.setAutoFix(Boolean.parseBoolean(newValue));
                break;
            default:
                throw new AttributeNotFoundError();
        }
        customerRepository.save(user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "更改成功");
        jsonObject.put("oldValue", oldValue);
        jsonObject.put("newValue", newValue);
        return jsonObject;
    }

    @Operation(description = "分页获取用户的信息，注意这是一个管理接口，即只有管理员才有权限访问。" +
            "可以使用的排序依据有【userName、userNickName、userPhone、userRoleId（角色编号）、" +
            "mouthElectricity（当月耗电度数）、totalChargeHour（总充电时长）、totalOverTimeHour（总超时时间）、" +
            "totalChargeTimes（总充电次数）、signUpDate（注册时间）】，使用其余排序依据会返回错误码。")
    @GetMapping("admin/{orderBy}/{page}/{pageNum}/{asc}")
    public Page<Customer> getCustomerPage(@PathVariable("orderBy") String orderBy,   //排序依据
                                          @PathVariable("page") int page,            //页号
                                          @PathVariable("pageNum") int pageNum,      //每页数目
                                          @PathVariable("asc") boolean asc) {
        Pageable pageable = PageRequest.of(page - 1, pageNum, asc ? Sort.Direction.ASC : Sort.Direction.DESC, orderBy);
        Page<Customer> customerPage = customerRepository.findAll(pageable);
        List<Customer> customerList = customerPage.getContent();
        for (Customer customer : customerList) {
            customer.setUserPassword("*");
        }
        return customerPage;
    }

    @Operation(description = "")
    @GetMapping("bill")
    public List<Bill> getAllBill(HttpServletRequest httpServletRequest) {
        long userId = (long) httpServletRequest.getAttribute("customerId");
        return billService.getAllBillByCustomerId(userId);
    }

    @Operation(description = "")
    @GetMapping("bill/charging")
    public List<Bill> getChargingBill(HttpServletRequest httpServletRequest) {
        long userId = (long) httpServletRequest.getAttribute("customerId");
        return billService.getChargingBill(userId);
    }

}
